<!-- 仓库编辑弹窗 -->
<template>
  <ele-modal
    form
    :width="460"
    :model-value="modelValue"
    title="编辑开发者配置"
    @update:model-value="updateModelValue"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
      <el-form-item label="开发者ID" prop="xpyun_user">
        <el-input
          v-model.trim="form.xpyun_user"
          clearable
          placeholder="请输入开发者ID"
        />
      </el-form-item>
      <el-form-item label="开发者密钥" prop="xpyun_key">
        <el-input
          v-model.trim="form.xpyun_key"
          clearable
          placeholder="请输入开发者密钥"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="updateModelValue(false)">
        取消
      </el-button>
      <el-button
        type="primary"
        :loading="loading"
        @click="save"
      >
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script setup>
const props = defineProps({
  /** 弹窗是否打开 */
  modelValue: Boolean,
  /** 修改回显的数据 */
  data: Object,
})

const emit = defineEmits(['done', 'update:modelValue'])

/** 提交状态 */
const loading = ref(false)

/** 表单实例 */
const formRef = ref(null)

const [warehouseList] = utils.useGetList('/xpyun/wIdToXpyunList', { type: 1 })

/** 表单数据 */
const [form, , assignFields] = utils.useFormData({
  print_num: 1,
  xpyun_ids: [],
  product_ids: [],
})

/** 表单验证规则 */
const rules = reactive({
  print_num: {
    required: true,
    message: '请输入打印数量',
    type: 'string',
    trigger: 'blur',
  },
  xpyun_ids: {
    required: true,
    message: '请选择打印机',
    type: 'array',
    trigger: 'change',
  },
})

/** 保存编辑 */
function save() {
  formRef.value?.validate?.((valid) => {
    if (!valid)
      return

    loading.value = true
    utils.post('/xpyun/printProduct', form)
      .then((res) => {
        utils.message(res.msg, res.success)
        updateModelValue(false)
        emit('done')
      })
      .finally(() => {
        loading.value = false
      })
  })
}

/** 更新modelValue */
function updateModelValue(value) {
  emit('update:modelValue', value)
}

watch(
  () => props.modelValue,
  (modelValue) => {
    if (modelValue) {
      if (props.data) {
        assignFields(props.data)
      }
    }
    else {
      formRef.value?.clearValidate?.()
    }
  },
)
</script>
